挑戰 Codewars LV3 題目
Create a simple calculator that given a string of operators (), +, -, *, / and numbers separated by spaces returns the value of that expression
Example:
Calculator.new.evaluate("2 / 2 + 3 * 4 - 6") # => 7
Remember about the order of operations! Multiplications and divisions have a higher priority and should be performed left-to-right. Additions and subtractions have a lower priority and should also be performed left-to-right.
class Calculator
def evaluate(string)
end
end
calc = Calculator.new
Test.assert_equals(calc.evaluate("4 + 5"), 9)
Test.assert_equals(calc.evaluate("4 * 5"), 20)
Test.assert_equals(calc.evaluate("4 / 5"), 0.8)
Test.assert_equals(calc.evaluate("4 - 5"), -1)
Test.assert_equals(calc.evaluate("4 + 5 * 6"), 34)
答案:
# Calculator
class Calculator
def evaluate(string)
['+', '-', '*', '/'].each do |cal|
if string.include?(cal)
return string.split(cal).map{ |x| evaluate(x) }.inject(cal.strip)
end
end
string.to_f
end
end
本文同步發布於 小菜的 Blog https://riverye.com/